<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 2017/7/20
 * Time: 下午4:57
 */
namespace backend\controllers;

use common\models\ar\ActivationDetail;
use common\models\ar\HistoryTemplateSet;
use common\models\ar\HistoryUserTemplateSet;
use common\models\ar\SysConfig;
use common\models\ar\Templates;
use common\models\ar\User;
use common\models\ar\UserTrade;
use common\models\Common;
use common\models\TemplateDao;
use common\models\UserDao;

class TemplateController extends BackendController
{
    /**
     * 模板列表
     */
    public function actionLists()
    {
        $level = \Yii::$app->user->identity->level;
        $levelInfo = Common::getLevelsInfo($level);
        $req = \Yii::$app->request;
        $isRender = $req->get('isRender', 1);//1为搜索页面，2为异步获取代理记录

        if ($isRender == 1) {
            $data = [];
            $data['is_first'] = $levelInfo['is_first'];
            $data['template_num'] = SysConfig::findOne(['key' => 'max_trade_cost_template_num'])->value;

            return $this->renderPartial('lists', $data);
        }

        $pageNo = (int)$req->get('pageNo', 1);
        $pageSize = \Yii::$app->params['pageSize'];

        if ($levelInfo['is_first']) {
            //平台级，可以根据代理用户进行搜索
            $clientSN = trim($req->get('clientSN', \Yii::$app->user->identity->clientSN));
            if (!$clientSN) {
                //所有模板
                $uid = -1;
            } else {
                $where['clientSN'] = $clientSN;

                $obj = User::find()->where($where)->one();
                if (!$obj) {
                    $uid = 0;
                } else {
                    $uid = $obj->uid;
                }
            }
        } else {
            //非平台级，只能看到自己的模板
            $uid = \Yii::$app->user->identity->uid;
        }

        $res = TemplateDao::lists($uid, $pageNo, $pageSize);
        $pageTotal = ceil($res['total'] / $pageSize);
        $return = [
            'uid' => \Yii::$app->user->identity->uid,
            'pageNo' => $pageNo,
            'pageTotal' => $pageTotal,
            'lists' => $res['lists'],
        ];
        exit(json_encode($return));
    }

    /**
     * 分配模板表单
     */
    public function actionAssignForm()
    {
        $req = \Yii::$app->request;
        $uidSession = \Yii::$app->user->identity->uid;
        $level = \Yii::$app->user->identity->level;
        $levelInfo = Common::getLevelsInfo($level);

        $type = (int)$req->get('type', 1);//1代理，2交易客户
        $uid = (int)$req->get('uid', 0);
        if ($type == 1) {
            $obj = User::findOne($uid);
        } else {
            $obj = UserTrade::findOne($uid);
        }

        if (!$obj || ($levelInfo['is_first'] != 1 && $obj->pid != $uidSession)) {
            exit("权限不足");
        }

        //手续费
        $tmp = TemplateDao::lists($obj->pid, 1, 1000);
        $info = TemplateDao::info($obj->template_id, 1);
        $templateInfo = [
            'templateID' => $obj->template_id,
            'lists' => $tmp['lists'],
            'info' => $info,
        ];

        return $this->renderPartial(
            'assign-form',
            [
                'type' => $type,
                'userInfo' => $obj,
                'templateInfo' => $templateInfo,
            ]
        );
    }

    /**
     * 为用户分配模板
     */
    public function actionAssign()
    {
        $level = \Yii::$app->user->identity->level;
        $levelInfo = Common::getLevelsInfo($level);

        $req = \Yii::$app->request;
        $uidSession = \Yii::$app->user->identity->uid;

        $templateID = (int)$req->post('template_id', 0);//手续费模板ID
        $uid = (int)$req->post('uid', 0);//受操作的用户ID
        $type = (int)$req->post('type', 1);//1代理，2交易客户

        if ($type == 1) {
            $obj = User::findOne($uid);
        } else {
            $obj = UserTrade::findOne($uid);
        }

        if (!$obj) {
            $code = 1001;
            $msg = "用户不存在";

            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if (isset($obj->status) && $obj->status != 1) {
            $code = 1001;
            $msg = "交易账户未开通";

            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($obj->pid != $uidSession) {
            $code = 1001;
            $msg = "权限不足";

            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($templateID == 0) {
            $code = 1002;
            $msg = "请选择要分配的手续费模板";

            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        //未变更
        $templateID_old = $obj->template_id;
        if ($templateID_old == $templateID) {
            $code = 1004;
            $msg = "请选择需要分配的新模板";

            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        /*** 手续费模板判断 ***/
        $errors = TemplateDao::assignTemplateCheck($uidSession, $uid, $templateID);

        if (!empty($errors)) {
            $code = 1005;
            $msg = implode('<br><br>', $errors);

            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        //为用户分配模板ID
        $obj->template_id = $templateID;
        $obj->save();

        //新模板+1，旧模板-1
        $templateInfo = Templates::findOne($templateID);
        $templateInfo->use_count = $templateInfo->use_count + 1;
        $templateInfo->save();

        $templateInfo = Templates::findOne($templateID_old);
        if ($templateInfo) {
            $templateInfo->use_count = $templateInfo->use_count - 1;
            $templateInfo->save();
        }
        unset($templateInfo);

        $history = new HistoryUserTemplateSet();
        $history->attributes = [
            'uid_operate' => $uidSession,
            'uid' => $uid,
            'direction' => $templateID_old == 0 ? 1 : 2,//1新增，2切换
            'template_id_new' => $templateID,
            'template_id_old' => $templateID_old,
            'time' => time(),
            'ip' => $req->userIP,
            'ua' => $req->userAgent
        ];
        $history->save();

        //如果是营业部，还需要通知到交易数据库
        if ($levelInfo['is_last'] == 1) {
            $tmp = UserTrade::findOne($uid);
            $tmp->save();
            TemplateDao::templateModifyNotify($templateID, 3, $uid);
        }

        exit(json_encode(['code' => 1, 'msg' => '分配成功']));
    }

    /**
     * 我的模板信息
     *
     * @return string
     */
    public function actionMy()
    {
        $lists = TemplateDao::my(\Yii::$app->user->identity->uid, 1);
        return $this->renderPartial('my', ['lists' => $lists]);
    }

    /**
     * 添加模板
     */
    public function actionAddForm()
    {
        $products = TemplateDao::my(\Yii::$app->user->identity->uid, 1);
        if (empty($products)) {
            exit("请联系您的上级为您设置品种的交易手续费");
        }

        $tmp = TemplateDao::lists(\Yii::$app->user->identity->uid, 1, 1000);
        $templates = $tmp['lists'];

        return $this->renderPartial('add-form', ['templates' => $templates, 'products' => $products]);
    }

    /**
     * 添加模板
     *
     * @return bool
     */
    public function actionAdd()
    {
        $req = \Yii::$app->request;
        if (!$req->isPost) {
            exit(json_encode(['code' => 0, 'msg' => 'Error Request']));
        }

        $uid = \Yii::$app->user->identity->uid;
        $myProducts = TemplateDao::my(\Yii::$app->user->identity->uid, 1);
        if (empty($myProducts)) {
            $code = 1001;
            $msg = '请联系您的上级为您设置品种的交易手续费';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $title = strip_tags(trim($req->post('title', '')));
        if (!$title) {
            $code = 1001;
            $msg = '请输入模板标题';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $desc = strip_tags(trim($req->post('desc', '')));
        $is_default = (int)$req->post('is_default', 0);
        $templatesCount = Templates::find()->where(['uid' => $uid, 'status' => 1])->count();
        $maxTradeCost = SysConfig::findOne(['key' => 'max_trade_cost'])->value;
        $maxTemplateNum = SysConfig::findOne(['key' => 'max_trade_cost_template_num'])->value;
        if ($templatesCount >= $maxTemplateNum) {
            $code = 1004;
            $msg = '可创建的最大模板数量为' . $maxTemplateNum;
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($templatesCount == 0) {
            //第一条必须为默认模板
            $is_default = 1;
        }

        //同一个用户模板名称不能重复
        $titleExist = Templates::find()
            ->where(['uid' => $uid, 'status' => 1, 'title' => $title])
            ->count();
        if ($titleExist) {
            $code = 1002;
            $msg = '模板标题已存在';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $ids_string = $req->post('ids', '');
        $ids = explode(',', $ids_string);
        if (count($ids) == 0) {
            $code = 1002;
            $msg = '模板中最少需要一个品种';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $detail = [];
        $errors = [];
        foreach ($ids as $id) {
            //不存在的ID不处理
            if (!isset($myProducts[$id])) {
                continue;
            }

            $tmpName = $myProducts[$id]['product'];
            $tradeCostOpen = (float)$req->post($id . "_open", 0);
            $tradeCostClose = (float)$req->post($id . "_close", 0);

            $minTradeCostOpen = $myProducts[$id]['trade_cost_open'];
            if ($tradeCostOpen < $minTradeCostOpen) {
                $errors[] = '品种 ' . $tmpName . ' 开仓手续费不能小于' . $minTradeCostOpen;
            }
            if ($tradeCostOpen > $maxTradeCost) {
                $errors[] = '品种 ' . $tmpName . ' 开仓手续费不能大于' . $maxTradeCost;
            }

            $minTradeCostClose = $myProducts[$id]['trade_cost_close'];
            if ($tradeCostClose < $minTradeCostClose) {
                $errors[] = '品种 ' . $tmpName . ' 平仓手续费不能小于' . $minTradeCostClose;
            }
            if ($tradeCostClose > $maxTradeCost) {
                $errors[] = '品种 ' . $tmpName . ' 平仓手续费不能大于' . $maxTradeCost;
            }

            $detail[] = [
                'product' => $tmpName,
                'trade_cost_open' => $tradeCostOpen,
                'trade_cost_close' => $tradeCostClose,
            ];
        }

        if (!empty($errors)) {
            exit(json_encode(['code' => 1003, 'msg' => implode('<br><br>', $errors)]));
        }

        $base = [
            'uid' => $uid,
            'is_default' => $is_default,
            'title' => $title,
            'desc' => $desc
        ];

        $bool = TemplateDao::add($base, $detail);

        if ($bool) {
            if ($templatesCount == 0) {
                $obj = new ActivationDetail();
                $obj->attributes = [
                    'uid' => $uid,
                    'item_id' => 6,
                    'time' => time()
                ];
                $obj->save();
                UserDao::activation($uid);
            }

            $code = 1;
            $msg = "添加成功";
        } else {
            $code = 0;
            $msg = "添加失败";
        }

        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }

    /**
     * 删除模板
     *
     * @return string
     */
    public function actionDel()
    {
        $uid = \Yii::$app->user->identity->uid;
        $id = \Yii::$app->request->get('id', 0);
        $obj = Templates::findOne($id);
        if (!$obj || $obj->status != 1 || $obj->uid != $uid) {
            $code = 1001;
            $msg = "权限不足";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($obj->use_count != 0) {
            $code = 1003;
            $msg = "模板已使用，不能删除";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($obj->is_default == 1) {
            $code = 1004;
            $msg = "默认模板，不能删除";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        //模板状态改为删除状态
        $obj->status = 2;
        $obj->save();

        //操作历史
        $time = time();
        $obj = new HistoryTemplateSet();
        $obj->attributes = [
            'uid' => $uid,
            'template_id' => $id,
            'direction' => 4,
            'time' => $time,
            'ip' => \Yii::$app->request->userIP,
            'ua' => \Yii::$app->request->userAgent,
            'info' => json_encode(['删除模板']),
        ];
        $obj->save();
        exit(json_encode(['code' => 1, 'msg' => '删除成功']));
    }

    /**
     * 获取模板中的品种以及手续费信息
     */
    public function actionDetail()
    {
        $uid = \Yii::$app->user->identity->uid;
        $level = \Yii::$app->user->identity->level;
        $levelInfo = Common::getLevelsInfo($level);

        $id = \Yii::$app->request->get('id', 0);
        $obj = Templates::findOne($id);

        if (!$obj || $obj->status != 1 || ($obj->uid != $uid && $levelInfo['is_first'] != 1)) {
            $code = 1001;
            $msg = "权限不足";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $res = TemplateDao::info($id, 3);
        $code = 1;
        $msg = 'ok';
        exit(json_encode(['code' => $code, 'msg' => $msg, 'detail' => $res['detail']]));
    }


    /**
     * 修改模板基本信息
     */
    public function actionModifyBaseForm()
    {
        $uid = \Yii::$app->user->identity->uid;
        $level = \Yii::$app->user->identity->level;
        $levelInfo = Common::getLevelsInfo($level);

        $id = \Yii::$app->request->get('id', 0);
        $obj = Templates::findOne($id);
        if (!$obj || $obj->status != 1 || ($obj->uid != $uid && $levelInfo['is_first'] != 1)) {
            return $this->renderPartial('modify-base-form', ['error' => '权限不足']);
        }

        $info = TemplateDao::info($id, 2);
        return $this->renderPartial('modify-base-form', ['info' => $info['base']]);
    }

    /**
     * 修改模板基本信息
     */
    public function actionModifyBase()
    {
        $req = \Yii::$app->request;
        if (!$req->isPost) {
            exit(json_encode(['code' => 0, 'msg' => 'Error Request']));
        }

        $uid = \Yii::$app->user->identity->uid;
        $id = $req->post('id', 0);
        $obj = Templates::findOne($id);
        if (!$obj || $obj->status != 1 || $obj->uid != $uid) {
            $code = 1001;
            $msg = '权限不足';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $title = strip_tags(trim($req->post('title', '')));
        if (!$title) {
            $code = 1002;
            $msg = '请输入模板标题';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $desc = strip_tags(trim($req->post('desc', '')));
        $is_default = (int)$req->post('is_default', 0);
        if ($obj->is_default == 1 && $is_default == 0) {
            $code = 1003;
            $msg = '当前模板为默认模板，不能设置为非默认模板';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $info_base = ['修改模板基本信息'];
        $modify = [];
        if ($is_default != $obj->is_default) {
            $modify['is_default'] = $is_default;
            $info_base['是否为默认模板'] = '是';
            $obj->is_default = $is_default;
            //将之前的默认模板改为非默认模板
            $tmp = Templates::find()->where(['uid' => $uid, 'is_default' => $is_default])->one();
            if ($tmp) {
                $tmp->is_default = 0;
                $tmp->save();
            }
        }

        if ($title != $obj->title) {
            //同一个用户模板名称不能重复
            $titleExist = Templates::find()->where([
                'uid' => $uid,
                'status' => 1,
                'title' => $title
            ])->count();
            if ($titleExist) {
                $code = 1004;
                $msg = '模板标题已存在';
                exit(json_encode(['code' => $code, 'msg' => $msg]));
            }

            $modify['title'] = $title;
            $info_base['模板标题'] = $title;
            $obj->title = $title;
        }
        if ($desc != $obj->desc) {
            $modify['desc'] = $desc;
            $info_base['模板描述'] = $desc;
            $obj->desc = $desc;
        }

        if (empty($modify)) {
            $code = 1004;
            $msg = '没有修改';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if (!$obj->save()) {
            $code = 0;
            $msg = '修改失败1';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $time = time();
        $objHistory = new HistoryTemplateSet();
        $objHistory->attributes = [
            'uid' => $uid,
            'template_id' => $id,
            'direction' => 2,
            'time' => $time,
            'ip' => \Yii::$app->request->userIP,
            'ua' => \Yii::$app->request->userAgent,
            'info' => json_encode($info_base),
        ];
        if (!$objHistory->save()) {
            $code = 0;
            $msg = '修改失败2';
        } else {
            $code = 1;
            $msg = '修改成功';

            //如果是营业部，还需要通知到交易数据库
            $level = \Yii::$app->user->identity->level;
            $levelInfo = Common::getLevelsInfo($level);
            if ($levelInfo['is_last'] == 1) {
                TemplateDao::templateModifyNotify($obj->id, 1, 0);
            }
        }
        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }

    /**
     * 修改模板详细信息
     */
    public function actionModifyDetailForm()
    {
        $uid = \Yii::$app->user->identity->uid;
        $level = \Yii::$app->user->identity->level;
        $levelInfo = Common::getLevelsInfo($level);

        $id = \Yii::$app->request->get('id', 0);
        $obj = Templates::findOne($id);

        if (!$obj || $obj->status != 1 || ($obj->uid != $uid && $levelInfo['is_first'] != 1)) {
            exit("权限不足");
        }

        $info = TemplateDao::info($id, 3);
        $detail = $info['detail'];
        $products = TemplateDao::my(\Yii::$app->user->identity->uid, 1);
        return $this->renderPartial('modify-detail-form', [
            'template_id' => $id,
            'products' => $products,
            'detail' => $detail,
        ]);
    }

    /**
     * 更改手续费
     */
    public function actionModifyDetail()
    {
        $req = \Yii::$app->request;
        if (!$req->isPost) {
            return false;
        }

        $uid = \Yii::$app->user->identity->uid;
        $level = \Yii::$app->user->identity->level;
        $levelInfo = Common::getLevelsInfo($level);

        $template_id = (int)$req->post('template_id', 0);
        $objTemplate = Templates::findOne($template_id);
        if (!$objTemplate || $objTemplate->status != 1 || $objTemplate->uid != $uid) {
            $code = 1001;
            $msg = "权限不足";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $min_product_trade_cost_open = [];//下级各品种最小开仓手续费
        $min_product_trade_cost_close = [];//下级各品种最小平仓手续费
        if ($objTemplate->use_count != 0 && !$levelInfo['is_last']) {
            $used_userIDs = []; //使用该模板的下级
            $subTemplateIDs = [];//下级创建的模板库

            $tmp = User::find()
                ->select('uid')
                ->where(['template_id' => $template_id])
                ->all();

            foreach ($tmp as $v) {
                $used_userIDs[] = $v->uid;
            }

            if (!empty($used_userIDs)) {
                $tmp = Templates::find()
                    ->where('uid in (' . implode(',', $used_userIDs) . ')')
                    ->all();
                foreach ($tmp as $v) {
                    $subTemplateIDs[] = $v->id;
                }

                if (!empty($subTemplateIDs)) {
                    //去查找各品种的最小手续费
                    $sql = "SELECT 
                              `product`,
                              MIN(`trade_cost_open`) min_trade_cost_open,
                              MIN(`trade_cost_close`) min_trade_cost_close
                            FROM 
                              `templates_detail` 
                            WHERE 
                              `template_id` in (" . implode(',', $subTemplateIDs) . ") 
                            GROUP BY `product`
                    ";

                    $tmp = \Yii::$app->db->createCommand($sql)->queryAll();
                    foreach ($tmp as $v) {
                        $min_product_trade_cost_open[$v['product']] = $v['min_trade_cost_open'];
                        $min_product_trade_cost_close[$v['product']] = $v['min_trade_cost_close'];
                    }
                }
            }
        }

        $myProducts = TemplateDao::my(\Yii::$app->user->identity->uid, 1);
        $ids_string = $req->post('ids', '');
        $ids = explode(',', $ids_string);

        $detail = [];
        $errors = [];
        $maxTradeCost = SysConfig::findOne(['key' => 'max_trade_cost'])->value;
        foreach ($ids as $id) {
            //不存在的ID和末变化的手续费不处理
            if (!isset($myProducts[$id])) {
                continue;
            }

            $tradeCostOpen = (float)$req->post($id . "_open", 0);
            $tradeCostClose = (float)$req->post($id . "_close", 0);

            //手续费不能小于本账户的手续费
            $tmpName = $myProducts[$id]['product'];
            $tmpTradeCostOpen = $myProducts[$id]['trade_cost_open'];
            if ($tradeCostOpen < $myProducts[$id]['trade_cost_open']) {
                $errors[] = '品种 ' . $tmpName . ' 开仓手续费不能小于' . $tmpTradeCostOpen;
            }

            //查看下级模板库中已分配此品种的手续费，如果比设置的值小则不能设置
            if (isset($min_product_trade_cost_open[$id]) && $tradeCostOpen > $min_product_trade_cost_open[$id]) {
                $errors[] = '品种 ' . $tmpName . ' 开仓手续费不能大于' . $min_product_trade_cost_open[$id];
            } else {
                if ($tradeCostOpen > $maxTradeCost) {
                    $errors[] = '品种 ' . $tmpName . ' 开仓手续费不能大于' . $maxTradeCost;
                }
            }

            $tmpTradeCostClose = $myProducts[$id]['trade_cost_close'];
            if ($tradeCostClose < $myProducts[$id]['trade_cost_close']) {
                $errors[] = '品种 ' . $tmpName . ' 平仓手续费不能小于' . $tmpTradeCostClose;
            }

            //查看下级模板库中已分配此品种的手续费，如果比设置的值小则不能设置
            if (isset($min_product_trade_cost_close[$id]) && $tradeCostClose > $min_product_trade_cost_close[$id]) {
                $errors[] = '品种 ' . $tmpName . ' 平仓手续费不能大于' . $min_product_trade_cost_close[$id];
            } else {
                if ($tradeCostClose > $maxTradeCost) {
                    $errors[] = '品种 ' . $tmpName . ' 开仓手续费不能大于' . $maxTradeCost;
                }
            }

            $detail[] = [
                'product' => $id,
                'trade_cost_open' => $tradeCostOpen,
                'trade_cost_close' => $tradeCostClose
            ];
        }
        if (!empty($errors)) {
            exit(json_encode(['code' => 1003, 'msg' => implode('<br><br>', $errors)]));
        }

        $bool = TemplateDao::updateTradeCost($uid, $template_id, $detail);
        if ($bool) {
            $code = 1;
            $msg = "修改成功";

            //如果是营业部，还需要通知到交易数据库
            if ($levelInfo['is_last'] == 1) {
                TemplateDao::templateModifyNotify($template_id, 2, 0);
            }

        } else {
            $code = 0;
            $msg = "修改失败";
        }

        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }
}
